package cn.ssm.controller;


import cn.ssm.pojo.User;
import cn.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public String login(HttpSession session,@RequestParam("username") String username, @RequestParam("password") String password, Map<String, Object> map) {
        User login = userService.login(username, password);
        if (login!=null){
            //登录成功
            session.setAttribute("loginUser", username);
            session.setAttribute("loginUrl",login.getUsername());
            // 防止表单重复提交，通过重定向到主页, 需要添加一个视图
            return "redirect:/main.html";
        }
        map.put("msg", "用户名或密码错误！");
        return "/main/login"; }
    /**
     * 退出登录
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        //1. 清空session中的用户信息
        session.removeAttribute("loginUser");
        //2. 再将session进行注销
        session.invalidate();
        //3. 返回登录页面
        return "redirect:/index.html";
    }
}